package report

import (
	"../common"
	"../web"
	"strings"
)

type QueryItemObj struct {
	common.BaseHandler
}

func (self *QueryItemObj) Prepare() {}

func (self *QueryItemObj) ParameterCheck() bool {
	s_item := self.Ctx.Params["q"]
	if s_item != "" {
		self.Sqlparas = append(self.Sqlparas, s_item)
		self.SqlQueryExecute()
		return false
	} else {
		s_item = strings.TrimSpace(self.Ctx.Params["item"])
	}
	if s_item == "" {
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_item)

	return true
}

func (self *QueryItemObj) SqlQueryExecute() {
	items := *common.FetchOneRowPtr(
		`SELECT '1',ITEM,ISNULL(DESCRIP,''),ISNULL(FREQUENCYS,''),ISNULL(LIMIT,''),
				 ISNULL(ROUTING,''),ISNULL(PRODTYPE,''),ISNULL(PRODCODE,''),
				 ISNULL(FACTORYCODE,''),PACKQTY,CASE LOCKED WHEN 1 THEN 'Y' ELSE 'N' END 
           FROM SFC_ITEMS(NOLOCK)
          WHERE ITEM=?`,
		self.Usr.Conn, new(common.ItemDefine), self.Sqlparas...)
	testinfo := *common.FetchAllRowsPtr(
		`SELECT ITEM,PARAMETER,TESTNAME,FREQUENCY,PORT,SPECIFICATION
           FROM SFC_ITEMSTEST(NOLOCK) 
          WHERE ITEM=?
          ORDER BY ITEM, IDX`,
		self.Usr.Conn, new(common.PassiveFrequency), self.Sqlparas...)
	wo_details := *common.FetchAllRowsPtr(
		`SELECT TOP 200 ROW_NUMBER() OVER(ORDER BY MODIFYDATE DESC) AS IDX,WONO,ITEM,
				REV,QTY,ROUTING,CASE RELEASED WHEN 1 THEN 'Y' ELSE 'N' END AS RELEASED,
				RELEASEDQTY,CASE CLOSED WHEN 1 THEN 'Y' ELSE 'N' END AS CLOSED,
				CASE LOCKED WHEN 1 THEN 'Y' ELSE 'N' END AS LOCKED
		   FROM SFC_WO(NOLOCK) 
		  WHERE ITEM=?`,
		self.Usr.Conn, new(common.WorkInfo), self.Sqlparas...)

	self.TmplData["items"] = items
	self.TmplData["testinfo"] = testinfo
	self.TmplData["wo_details"] = wo_details
}

func QueryItemHandler(ctx *web.Context) {
	self := new(QueryItemObj)
	self.Ctx = ctx
	self.Html = "queryitem.html"
	self.Rightlist = []string{"queryitem"}
	self.DoQuery(self)
}
